﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	public class BackConnOperation : ConnOperation
	{
		public BackConnOperation(UIDocument uiDoc) : base(uiDoc)
		{
		}

		public override bool SelectDucts()
		{
			bool flag = false;
			if (this.SelectDuctsMethod != null)
			{
				string errorString = "";
				IList<Duct> source = null;
				IList<XYZ> source2 = null;
				flag = this.SelectDuctsMethod.ConnDuctsSelecting(ConnDuctSelectType.BackConn, ref source, ref source2, ref errorString);
				if (flag)
				{
					base.SelectedDucts = source.ToList<Duct>();
					base.SelectedPoints = source2.ToList<XYZ>();
				}
				else
				{
					base.ErrorString = errorString;
				}
			}
			return flag;
		}

		public override bool Connect()
		{
			bool flag = false;
			if (base.SelectedDucts.Count < 1)
			{
				base.ErrorString = "选择的风管个数不对！";
				return flag;
			}
			HYDuctConnect hyductConnect = new HYDuctConnect();
			ConnectDuctManage connectDuctManage = new ConnectDuctManage();
			if (!connectDuctManage.BeSameShapeDucts(base.SelectedDucts))
			{
				base.ErrorString = "选择的风管截面必须一致！";
				return flag;
			}
			ConnectDuctStyle connStyle = base.ConnForm.connStyle;
			connectDuctManage.GetDuctShape(base.SelectedDucts[0]);
			string empty = string.Empty;
			if (!(base.UIDoc.Document.GetElementById(base.SelectedDucts[0].DuctType.RoutingPreferenceManager.GetRule((RoutingPreferenceRuleGroupType)4, 0).MEPPartId) is FamilySymbol))
			{
				base.ErrorString = "布管配置中变径配置为空，请检查Revit的族配置";
				return flag;
			}
			List<string> fittingNames = connectDuctManage.GetFittingNames(connStyle);
			if (fittingNames.Count != 1)
			{
				base.ErrorString = "获取弯头族名称失败！";
				return false;
			}
			FamilySymbol familySymbol = connectDuctManage.GetFamilySymbol(fittingNames[0], base.UIDoc.Document, ref empty);
			if (familySymbol == null)
			{
				base.ErrorString = empty;
				return false;
			}
			IList<FamilyInstance> list = hyductConnect.NewLHWFitting(base.SelectedDucts, true, familySymbol, ref empty);
			if (list != null && list.Count > 0)
			{
				flag = true;
				base.UIDoc.Document.Regenerate();
			}
			if (!flag)
			{
				base.ErrorString = empty;
			}
			return flag;
		}
	}
}
